﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using BoardPACDSBO.Base;
using BoardPACDSDAO.Entity;
using System.Web.Security;
using System.Data.Objects;
using BoardPACDSDAO.Base;
using BoardPACUtil.Util;


namespace BoardPACDAO.Base
{
    public class BaseDAO
    {
        public BaseServiceModel Authorize(int customUserId, int type, int RefId, string actionString, int PasswordExpiryPeriod, string fmt, string userName)
        {
            BaseServiceModel baseServiceModel = new BaseServiceModel();
            try
            {
                using (BoardAppProductEntities entities = DataObjectFactory.CreateContext())
                {
                    string[] userroles = null;

                    if (!String.IsNullOrWhiteSpace(userName))
                    {
                        //checks whether the logged in user's password has expired; if so blocks all menu actions
                        if ((Membership.GetUser(userName).LastPasswordChangedDate.AddDays(PasswordExpiryPeriod) - DateTime.Now).Days >= 0 || (string.Compare(fmt, "XML", true) == 0))
                        {
                            userroles = Roles.GetRolesForUser(userName);
                        }
                        else
                        {
                            //userroles = Roles.GetRolesForUser("emptyRole");
                            userroles = new string[] { "emptyRole" };
                        }

                        baseServiceModel.userroles = userroles;
                    }
                    else //2012-08-22  added to avoid unnecessary errorlog entry before logging in.
                    {
                        //EventLog.Info(String.Format(Resources.log_evt_success_IsAuthorizedOptimized, EventStatus.Success.ToString(), fmt));
                        //Logs.WriteLogToDb(String.Format(Resources.log_evt_success_IsAuthorizedOptimized, EventStatus.Success.ToString(), fmt));
                        //throw new MemberNullException();
                    }
                    if (!"emptyRole".Equals(userroles.First()))
                    {
                        ObjectResult<sp_GetRolesinLevels_Result> LevelBasedActions = entities.sp_GetRolesinLevels(customUserId, type, RefId);
                        RolesByLevel rolesbyLevel = new RolesByLevel();
                        foreach (var item in LevelBasedActions) // This will only run once.
                        {
                            rolesbyLevel.GlobalActions = item.GlobalActions;
                            rolesbyLevel.CategoryActions = item.CategoryActions;
                            rolesbyLevel.SubCategoryActions = item.SubCategoryActions;
                            rolesbyLevel.MeetingActions = item.MeetingActions;
                            rolesbyLevel.PaperActions = item.PaperActions;
                        }

                        RolesByLevel ActionsbyLevel = new RolesByLevel();

                        //Global Level
                        if (!String.IsNullOrWhiteSpace(rolesbyLevel.GlobalActions))
                        {
                            String AllGlobalActionsList = ActionsbyLevelLang.global.ToString();
                            ActionsbyLevel.GlobalActions = FilterActionsByLevel(rolesbyLevel.GlobalActions, AllGlobalActionsList);
                        }

                        //Category Level
                        if (String.IsNullOrWhiteSpace(rolesbyLevel.CategoryActions))
                        {
                            ActionsbyLevel.CategoryActions = rolesbyLevel.GlobalActions;
                        }

                        if (!String.IsNullOrWhiteSpace(rolesbyLevel.CategoryActions))
                        {
                            String AllCategoryActionsList = ActionsbyLevelLang._0.ToString();
                            ActionsbyLevel.CategoryActions = FilterActionsByLevel(rolesbyLevel.CategoryActions, AllCategoryActionsList);
                        }

                        //SubCategory Level
                        if (String.IsNullOrWhiteSpace(rolesbyLevel.SubCategoryActions))
                        {
                            ActionsbyLevel.SubCategoryActions = rolesbyLevel.CategoryActions;
                        }

                        if (!String.IsNullOrWhiteSpace(rolesbyLevel.SubCategoryActions))
                        {
                            String AllSubCategoryActionsList = ActionsbyLevelLang._1.ToString();
                            ActionsbyLevel.SubCategoryActions = FilterActionsByLevel(rolesbyLevel.SubCategoryActions, AllSubCategoryActionsList);
                        }

                        //Meeting Level
                        if (String.IsNullOrWhiteSpace(rolesbyLevel.MeetingActions))
                        {
                            ActionsbyLevel.MeetingActions = rolesbyLevel.SubCategoryActions;
                        }

                        if (!String.IsNullOrWhiteSpace(rolesbyLevel.MeetingActions))
                        {
                            String AllMeetingActionsList = ActionsbyLevelLang._2.ToString();
                            ActionsbyLevel.MeetingActions = FilterActionsByLevel(rolesbyLevel.MeetingActions, AllMeetingActionsList);
                        }

                        //Paper Level
                        if (String.IsNullOrWhiteSpace(rolesbyLevel.PaperActions))
                        {
                            ActionsbyLevel.PaperActions = rolesbyLevel.MeetingActions;
                        }

                        if (!String.IsNullOrWhiteSpace(rolesbyLevel.PaperActions))
                        {
                            String AllPaperActionsList = ActionsbyLevelLang._3.ToString();
                            ActionsbyLevel.PaperActions = FilterActionsByLevel(rolesbyLevel.PaperActions, AllPaperActionsList);
                        }

                        baseServiceModel.ActionsbyLevel = ActionsbyLevel;
                        //Global Actions are allowed as it is. Have to check
                        String ActionsAllowedforCurrentUser = ActionsbyLevel.GlobalActions + ActionsbyLevel.CategoryActions + ActionsbyLevel.SubCategoryActions + ActionsbyLevel.MeetingActions + ActionsbyLevel.PaperActions;
                        baseServiceModel.ActionsAllowedforCurrentUser = ActionsAllowedforCurrentUser;

                        if (!String.IsNullOrWhiteSpace(ActionsAllowedforCurrentUser) && ActionsAllowedforCurrentUser.Contains(actionString))
                        {
                            baseServiceModel.Authorized = true;
                        }
                    }
                }
            }
            catch (GenServiceException)
            {
                throw;
            }
            catch (Exception)
            {
                throw;
            }
            return baseServiceModel;
        }

        public String FilterActionsByLevel(String levelActions, String allActions)
        {
            List<String> levelActionsList = levelActions.Split(',').ToList();
            List<String> levelAllActionsList = allActions.Split(',').ToList();
            List<String> similarity = levelActionsList.Intersect(levelAllActionsList).ToList();

            String temp = String.Empty;

            foreach (var item in similarity)
            {
                temp = temp + item + ", ";
            }
            return temp;
        }

        public static int AddLog(AuditLogModel auditLogModel)
        {
            try
            {
                using (BoardAppProductEntities entities = DataObjectFactory.CreateContext())
                {
                    AuditLog log = new AuditLog
                    {
                        Date = auditLogModel.Date,
                        EventNumber = auditLogModel.EventNumber,
                        Event = auditLogModel.EventOrError,
                        EventStatus = auditLogModel.EventStatus,
                        UserName = auditLogModel.UserName,
                        ControllerName = auditLogModel.ControllerName,
                        ActionName = auditLogModel.ActionName,
                        Parameters = auditLogModel.Parameters
                    };

                    entities.AuditLogs.AddObject(log);
                    entities.SaveChanges();
                    return log.LogId;
                }
            }
            catch (GenServiceException)
            {
                throw;
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
